package cn.iocoder.yudao.module.system.service.copying;

import cn.iocoder.yudao.framework.common.enums.YesOrNoEnum;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.util.*;

import cn.iocoder.yudao.module.system.controller.admin.copying.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.copying.CopyingDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.system.dal.mysql.copying.CopyingMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * 文案 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class CopyingServiceImpl implements CopyingService {

    @Value("${yudao.copying.id}")
    private Long copyingId;

    @Resource
    private CopyingMapper copyingMapper;

    private void setNotUse() {
        LambdaUpdateWrapper<CopyingDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(CopyingDO::getUsed, YesOrNoEnum.NO.getCode())
                .gt(CopyingDO::getId, 0);
        copyingMapper.update(lambdaUpdateWrapper);
    }

    @Override
    public Long createCopying(CopyingSaveReqVO createReqVO) {
        if (Objects.isNull(createReqVO.getUsed())) {
            createReqVO.setUsed(YesOrNoEnum.NO.getCode());
        }
        if (YesOrNoEnum.YES.getCode().equals(createReqVO.getUsed())) {
            setNotUse();
        }
        // 插入
        CopyingDO copying = BeanUtils.toBean(createReqVO, CopyingDO.class);
        copyingMapper.insert(copying);
        // 返回
        return copying.getId();
    }

    @Override
    public void updateCopying(CopyingSaveReqVO updateReqVO) {
        // 校验存在
        validateCopyingExists(updateReqVO.getId());
        // 更新
        CopyingDO updateObj = BeanUtils.toBean(updateReqVO, CopyingDO.class);
        if (YesOrNoEnum.YES.getCode().equals(updateReqVO.getUsed())) {
            setNotUse();
        }
        copyingMapper.updateById(updateObj);
    }

    @Override
    public void deleteCopying(Long id) {
        // 校验存在
        validateCopyingExists(id);
        // 删除
        copyingMapper.deleteById(id);
    }

    private void validateCopyingExists(Long id) {
        if (copyingMapper.selectById(id) == null) {
            throw exception(COPYING_NOT_EXISTS);
        }
    }

    @Override
    public CopyingDO getCopying(Long id) {
        return copyingMapper.selectById(id);
    }

    @Override
    public PageResult<CopyingDO> getCopyingPage(CopyingPageReqVO pageReqVO) {
        return copyingMapper.selectPage(pageReqVO);
    }

}